import { defineStore } from "pinia";
import { toRefs, reactive } from "vue";
import type { User } from "@/types";
import { get_req, req } from "@/api/req";

export default defineStore("permission", () => {
  const state = reactive({
    token: uni.getStorageSync("token") || "",
    regionHeader: uni.getStorageSync("regionHeader") || "",
    tenantId: uni.getStorageSync("tenantId") || "",
    tenantName: uni.getStorageSync("tenantName") || "",
    user: uni.getStorageSync("user") || ({} as User | null),
    memus: uni.getStorageSync("memus") || [],
    permissions: uni.getStorageSync("permissions") || [],
    roles: uni.getStorageSync("permissions") || [],
  });

  /**
   * 获取用户权限信息
   */
  async function getPermissionInfo() {
    const { data } = await get_req(
      "/app-api/system/workbench/auth/get-permission-info",
      { systemType: import.meta.env.VITE_APP_SYSTEM_TYPE }
    );
    state.user = data.user;
    state.memus = data.menus;
    state.memus = data.permissions;
    state.memus = data.roles;
    uni.setStorageSync("user", data.user);
    uni.setStorageSync("memus", data.menus);
    uni.setStorageSync("permissions", data.permissions);
    uni.setStorageSync("roles", data.roles);
  }

  /**
   * 登录账号密码登录
   * @param info 账号密码登录信息
   */
  async function accountLogin(info: Record<string, any>) {
    console.log("accountLogin", info);
    // 调用请求接口并获取返回的数据
    const res: any = await req("/zt/login/appLogin/" + info.username);
    console.log("result", res);
    state.token = res.result.token;
    uni.setStorageSync("token", res.result.token);
    /*
    state.tenantId = data.tenantId
    state.tenantName = info.tenantName
    state.regionHeader = data.regionHeader
    uni.setStorageSync('tenantId', data.tenantId)
    uni.setStorageSync('tenantName', info.tenantName)
    uni.setStorageSync('regionHeader', data.regionHeader)
    */
    await getPermissionInfo();
  }

  /**
   * 退出登录
   */
  async function logout() {
    await req("/app-api/system/workbench/auth/logout");
    state.token = "";
    state.user = {} as User | null;
    state.tenantId = "";
    state.tenantName = "";
    state.regionHeader = "";
    state.memus = [];
    state.permissions = [];
    state.roles = [];
    await uni.removeStorage({
      key: "cookies",
    });
    await uni.removeStorage({
      key: "token",
    });
    await uni.removeStorage({
      key: "tenantId",
    });
    await uni.removeStorage({
      key: "tenantName",
    });
    await uni.removeStorage({
      key: "regionHeader",
    });
    await uni.removeStorage({
      key: "user",
    });
    await uni.removeStorage({
      key: "memus",
    });
    await uni.removeStorage({
      key: "permissions",
    });
    await uni.removeStorage({
      key: "roles",
    });
  }

  return {
    ...toRefs(state),
    nickname: computed(() => state.user?.real_name || ""),
    accountLogin,
    logout,
  };
});
